﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using XcoAppSpaces.Contracts.Service;
using XcoAppSpaces.Contracts.Exceptions;

namespace XcoAppSpaces.Discovery
{
	public class ConfigStringInterpreter : XcoConfigStringInterpreterBase
	{
		public const string ConfigIsServer = "disco.isserver";
		public const string ConfigAddress = "disco.address";

		private bool? isServer;
		private string address;
		
		public override Dictionary<string, Action<string>> InterpretDefinition
		{
			get
			{
				return new Dictionary<string, Action<string>> 
                    { 
                        {ConfigIsServer, ProcessIsServer},
                        {ConfigAddress, ProcessAddress},
                    };
			}
		}

		public override IXcoService GetService
		{
			get
			{
				if (isServer != null && isServer.Value)
				{
					if (address != null)
						throw new XcoConfigurationException("Discovery service cannot be server and refer to another address at the same time!");
					return new XcoDiscoveryService();
				}
				if (address != null)
					return new XcoDiscoveryService(address);
				return null;
			}
		}

		void ProcessAddress(string value)
		{
			this.address = value;
		}

		void ProcessIsServer(string value)
		{
			bool boolValue;
#if PocketPC
			if (ParseHelper.TryParse(value, out boolValue))
#else
			if (bool.TryParse(value, out boolValue))
#endif
			{
				isServer = boolValue;
			}
			else
			{
				throw new XcoConfigurationException("disco.isserver must be either \"true\" or \"false\"!");
			}
		}
	}
}
